<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <!-- <a-button type="primary" @click="handleForm({})" v-auth="'wh:pd:whPdStockBill:edit'">
          <Icon icon="i-fluent:add-12-filled" /> {{ t('新增') }}
        </a-button> -->
        <!-- <a-button type="primary" @click="handleForm({})" v-auth="'wh:pd:whPdStockPosBill:edit'">
          <Icon icon="i-fluent:add-12-filled" /> {{ t('新增') }}
        </a-button> -->

        <!--  <a-button type="default" @click="handleExport()">
          <Icon icon="i-ant-design:download-outlined" /> {{ t('导出') }}
        </a-button> -->
        <Popconfirm title="确认生成盘盈盘亏吗？" @confirm="handleGenerateTask({})">
          <a-button type="dashed" success v-auth="'wh:pd:whPdStock:edit'">
            <Icon icon="i-ant-design:check-outlined" /> {{ t('生成盘盈盘亏') }}
          </a-button>
        </Popconfirm>
        <Popconfirm :title="t('确认完成盘点吗?')" @confirm="handleGenerateTask2({})">
          <a-button type="default" v-auth="'wh:pd:whPdStockPosBill:pd'">
            <Icon icon="i-ant-design:check-outlined" /> {{ t('完成盘点') }}
          </a-button>
        </Popconfirm>
        <a-button type="default" @click="handlePrint({})" v-auth="'wh:pd:whPdStock:edit'">
          <Icon icon="simple-line-icons:printer" /> {{ t('打印') }}
        </a-button>
        <Popconfirm :title="t('确认作废吗?')" @confirm="handleZf({})">
          <a-button type="default" v-auth="'wh:pd:whPdStockPosBill:cancel'">
            <Icon icon="i-carbon:close" /> {{ t('作废') }}
          </a-button>
        </Popconfirm>
        <a-button type="success" ghost @click="handleFormWh({})" v-auth="'wh:pd:whPdStock:edit'">
          <Icon icon="i-fluent:add-12-filled" /> {{ t('按仓库/货位盘点') }}
        </a-button>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleFormWh({ djno: record.djno })">
          {{ record.djno }}
        </a>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <FormWh @register="registerDrawerWh" @success="handleSuccess" />
    <PrintModal @register="registerPrintModal" />
  </div>
</template>
<script lang="ts" setup name="ViewsWmsWhPdWhPdStockPosBillList">
  import { unref, onMounted } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import {
    whPdStockPosBillDelete,
    whPdStockPosBillListData,
    createRdBill,
    overPdPosData,
    cancelData,
  } from '/@/api/wms/wh/pd/whPdStockPosBill';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import InputForm from './form.vue';
  import FormWh from '/@/views/wms/wh/pd/whPdStockPosBill/formWh.vue';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import { Popconfirm } from 'ant-design-vue';
  import { companyTreeData } from '/@/api/sys/company';
  import { useUserStore } from '/@/store/modules/user';
  import { useModal } from '/@/components/Modal';
  import PrintModal from '/@/components/print/printModal.vue';

  const { t } = useI18n('wh.pd.whPdStockPosBill');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const userStore = useUserStore();

  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: meta.title || t('盘点管理'),
  };

  onMounted(() => {
    setProps({});
    handleCompany();
  });

  async function handleCompany() {
    await getForm().setFieldsValue({
      companyCode: userStore.getProjecte.code,
    });
    reload();
    await getForm().setFieldsValue({
      companyCode: userStore.getProjecte.code,
    });
  }

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      {
        label: t('公司'),
        field: 'companyCode',
        fieldLabel: 'companyName',
        component: 'TreeSelect',
        componentProps: {
          api: companyTreeData,
          allowClear: true,
          immediate: true,
          onChange: handleSuccess,
        },
      },
      {
        label: t('盘点方式'),
        field: 'pdType',
        component: 'Select',
        componentProps: {
          dictType: 'wms_pd_type',
          allowClear: true,
        },
      },
      {
        label: t('单据日期'),
        field: 'ddate',
        component: 'DatePicker',
        componentProps: {
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD 00:00:00',
        },
      },
      {
        label: t('单据号'),
        field: 'djno',
        component: 'Input',
      },
      {
        label: t('盘点状态'),
        field: 'pdStatus',
        component: 'Select',
        componentProps: {
          dictType: 'wms_pd_status',
          allowClear: true,
        },
      },
      {
        label: t('单据状态'),
        field: 'status',
        component: 'Select',
        componentProps: {
          dictType: 'wms_pd_zf_status',
          allowClear: true,
        },
      },
      {
        label: t('仓库'),
        field: 'basWare.cwhname',
        component: 'Input',
      },
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('公司名称'),
      dataIndex: 'company.companyName',
      key: 'a.company_name',
      // sorter: true,
      width: 200,
      align: 'left',
    },
    {
      title: t('单据号'),
      dataIndex: 'djno',
      key: 'a.djno',
      sorter: true,
      width: 130,
      align: 'center',
      slot: 'firstColumn',
    },
    {
      title: t('盘点方式'),
      dataIndex: 'pdType',
      key: 'a.pd_type',
      sorter: true,
      width: 230,
      align: 'left',
      dictType: 'wms_pd_type',
      // slot: 'firstColumn',
    },
    {
      title: t('单据日期'),
      dataIndex: 'ddate',
      key: 'a.ddate',
      sorter: true,
      width: 130,
      align: 'center',
      customRender: ({ record }) => {
        return formatDate(record.ddate);
      },
    },
    {
      title: t('盘点状态'),
      dataIndex: 'pdStatus',
      key: 'a.pd_status',
      dictType: 'wms_pd_pdStatus',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('单据状态'),
      dataIndex: 'status',
      key: 'a.status',
      dictType: 'wms_pd_zf_status',
      sorter: true,
      width: 100,
      align: 'left',
    },
    {
      title: t('总数'),
      dataIndex: 'iqty',
      key: 'a.iqty',
      sorter: true,
      width: 130,
      align: 'right',
      showSummary: true,
      showTotalSummary: true,
    },
    {
      title: t('实盘总数'),
      dataIndex: 'sumqty',
      key: 'a.sumqty',
      sorter: true,
      width: 130,
      align: 'right',
      showSummary: true,
      showTotalSummary: true,
    },
    {
      title: t('仓库'),
      dataIndex: 'basWare.cwhname',
      key: 'a.whcode',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('货位'),
      dataIndex: 'posName',
      key: 'a.pos_name',
      sorter: true,
      width: 130,
      align: 'left',
    },
  ];

  const actionColumn: BasicColumn = {
    width: 160,
    actions: (record: Recordable) => [
      {
        icon: 'i-clarity:note-edit-line',
        title: t('编辑盘点'),
        onClick: handleFormWh.bind(this, { djno: record.djno }),
        // status:  为 2 不允许编辑
        ifShow: record.pdStatus === '0' && record.status !== '2',
        auth: 'wh:pd:whPdStockPosBill:edit',
      },
      {
        icon: 'i-ant-design:delete-outlined',
        color: 'error',
        title: t('删除盘点'),
        popConfirm: {
          title: t('是否确认删除盘点'),
          confirm: handleDelete.bind(this, record),
        },
        ifShow: record.pdStatus === '0' && record.status !== '2',
        auth: 'wh:pd:whPdStockPosBill:edit',
      },
    ],
    showCustomSummary: true,
    showTotalCustomSummary: true,
    rowSelection: {
      type: 'checkbox',
    },
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerDrawerWh, { openDrawer: openDrawerWh }] = useDrawer();
  const [registerTable, { reload, getForm, getSelectRowKeys, setProps, getSelectRows }] = useTable({
    api: whPdStockPosBillListData,
    beforeFetch: (params) => {
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    showCustomSummary: true,
    showTotalCustomSummary: true,
    canResize: true,
    rowSelection: {
      type: 'checkbox',
    },
  });

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  async function handleDelete(record: Recordable) {
    const params = { djno: record.djno };
    const res = await whPdStockPosBillDelete(params);
    showMessage(res.message);
    handleSuccess(record);
  }

  function handleSuccess(record: Recordable) {
    reload({ record });
    console.log(record, 'record');
  }

  function handleFormWh(record: Recordable) {
    openDrawerWh(true, record);
  }

  async function handleGenerateTask2() {
    let arr = await getSelectRowKeys();
    if (getSelectRowKeys().length != 1) {
      showMessage(t('请选择一行数据'));
      return;
    }
    const selIds = arr.join(',');
    const params = { djno: selIds };
    // todo 生成任务API
    const res = await overPdPosData(params);
    console.log(res, 'res');
    showMessage(res.message);
    handleSuccess({});
  }

  async function handleExport() {
    const { ctxAdminPath } = useGlobSetting();
    downloadByUrl({
      url: ctxAdminPath + '/wh/pd/whPdStockBill/exportData',
      params: getForm().getFieldsValue(),
    });
  }

  // 格式化日期，只显示年月日
  function formatDate(dateStr: string): string {
    if (!dateStr) return '';

    try {
      // 如果日期字符串包含时间部分，只取日期部分
      if (dateStr.includes(' ')) {
        return dateStr.split(' ')[0];
      }

      // 如果是完整的日期格式，使用 Date 对象格式化
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) {
        return dateStr; // 如果无法解析，返回原始字符串
      }

      // 格式化为 YYYY-MM-DD
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');

      return `${year}-${month}-${day}`;
    } catch (error) {
      console.warn('日期格式化失败:', dateStr, error);
      return dateStr; // 出错时返回原始字符串
    }
  }

  const [registerPrintModal, { openModal: openPrintModal }] = useModal();
  async function handlePrint() {
    let arr = await getSelectRowKeys();
    if (getSelectRowKeys().length == 0) {
      showMessage(t('请先选择一行数据'));
      return;
    }
    let params = {
      ids: arr.join(','),
      title: '核对单',
      height: '0.9',
      width: '0.9',
      fileName: '核对单',
    };
    console.log(params, 'params');
    openPrintModal(true, params);
  }

  async function handleGenerateTask() {
    let arr = await getSelectRowKeys();
    if (getSelectRowKeys().length != 1) {
      showMessage(t('请选择一行数据'));
      return;
    }
    const selIds = arr.join(',');
    const params = { djno: selIds };
    const res = await createRdBill(params);
    console.log(res, 'res');
    showMessage(res.message);
    handleSuccess({});
  }
  async function handleZf() {
    let arr = await getSelectRowKeys();
    if (getSelectRowKeys().length != 1) {
      showMessage(t('请选择一行数据'));
      return;
    }
    const selIds = arr.join(',');
    const params = { id: selIds };
    // todo 生成任务API
    const res = await cancelData(params);
    console.log(res, 'res');
    showMessage(res.message);
    handleSuccess({});
  }
</script>
